package com.rpframework.module.common.bottom.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rpframework.core.json.EmptyException;
import com.rpframework.core.json.JsonResp;
import com.rpframework.module.common.bottom.entity.Menu;
import com.rpframework.module.common.bottom.service.MenuService;
import com.rpframework.module.common.bottom.service.TokenService;
import com.rpframework.module.common.bottom.service.WeixinMenuService;
import com.rpframework.module.common.config.WeixinConfig;
import com.rpframework.module.common.url.RequestDescription;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * 微信菜单控制层 ClassName:WeixinMenuController <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * Date: 2016年4月13日 下午4:23:19 <br/>
 *
 * @author Qiu ChengBing 745656220@qq.com
 * @since JDK 1.7
 */
@ResponseBody
@RequestMapping
@RequestDescription("微信菜单")
@Controller
public class WeixinMenuController {
    /**
     * 依赖关系
     */
    @Autowired
    private WeixinMenuService weixinMenuService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private MenuService menuService;

    @Autowired(required = false)
    private WeixinConfig weixinConfig;

    /**
     * 创建菜单
     *
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     * @author: Hermit 745656220@qq.com
     * @since JDK 1.7
     */
    @RequestMapping(value = "/createMenu")
    @Transactional(rollbackFor = Exception.class)
    public JsonResp<?> createMenu(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 获取菜单详情内容
        String jsonMenu = request.getParameter("menu");
        if (null == jsonMenu) {
            throw new EmptyException("菜单内容为空！");
        }
        JSONObject jsonObject = JSON.parseObject(jsonMenu);
        @SuppressWarnings("unchecked")
        List<JSONObject> button = jsonObject.getObject("button", List.class);
        // 取出url,进行解码后再重新装进JSON对象中

        for (int i = 0; i < button.size(); i++) {
            @SuppressWarnings("unchecked")
            List<JSONObject> jsonObject2 = button.get(i).getObject("sub_button", List.class);
            if (jsonObject2 != null) {
                for (int k = 0; k < jsonObject2.size(); k++) {
                    String type = jsonObject2.get(k).getString("type");
                    if ("view".equals(type)) {
                        String url = jsonObject2.get(k).getString("url");
                        url = URLDecoder.decode(url, "UTF-8");
                        jsonObject2.get(k).put("url", url);
                    }
                }
            }
        }
        // 把JSON对象转成字符串
        String menu = jsonObject.toString();
        // 查询token
        String accessToken = tokenService.findAccessToken(weixinConfig.getAppId());
        if (StringUtils.isBlank(accessToken)) {
            throw new EmptyException("accessToken密匙为空！");
        }
        Menu mn = new Menu();
        mn.setContent(menu);
        menuService.insertSelective(mn);
        int code = weixinMenuService.createWeixinMenu(menu, accessToken);

        if (code != 0) {
            // 删除数据库菜单
            menuService.deleteMenu();

            throw new EmptyException("微信创建菜单失败！");
        }
        return new JsonResp<>().succ("创建成功");
    }

    /**
     * 查询菜单json串
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectMenu")
    public JsonResp<?> selectMenu(HttpServletRequest request) {
        // 查询accessToken
        String accessToken = tokenService.findAccessToken(weixinConfig.getAppId());
        if (StringUtils.isBlank(accessToken)) {
            throw new EmptyException("accessToken密匙为空！");
        }
        // 调用查询菜单接口
        String menu = weixinMenuService.selectWeixinMenu(accessToken);
        if (null == menu) {
            throw new EmptyException("没有查到菜单JSON串！");
        }
        return new JsonResp<>().succ("创建成功", menu);
    }

    /**
     * 查询最后一条数据的菜单（数据库）
     */
    @RequestMapping(value = "/selectContent")
    public String selectContent(HttpServletRequest request) {
        Menu findMenu = menuService.findMenu();
        if (null == findMenu) {
            return "";
        }
        return findMenu.getContent();
    }
    
    
    /**
     * 添加永久素材
     */
    @RequestMapping(value = "/addMaterial")
    public JsonResp<?> addMaterial(HttpServletRequest request,String type,String mediaFileUrl) {
    	 String accessToken = tokenService.findAccessToken(weixinConfig.getAppId());
    	 try {
			mediaFileUrl = URLDecoder.decode(mediaFileUrl, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			 throw new EmptyException("地址编码异常！");
		}
    	 weixinMenuService.addMaterial(accessToken, type, mediaFileUrl);
    	 return new JsonResp<>().succ("创建成功");
    }
}
